package com.juqimiao.linn.command.mock;

import com.juqimiao.linn.command.CommandBus;
import com.juqimiao.linn.command.CommandHub;
import com.juqimiao.linn.command.CommandInvocation;
import com.juqimiao.linn.exception.FrameworkException;
import com.juqimiao.linn.transfer.Command;
import com.juqimiao.linn.transfer.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@Component("CompletableCommandBus")
public class CompletableCommandBus extends CommandBus {
   // @Autowired
   // private CommandHub commandHub;

    @Autowired
    public CompletableCommandBus(CommandHub commandHub) {
        super(commandHub);
    }

    @Override
    public Response send(Command baseCommand) {
        Response response = null;
        CommandInvocation invocation = super.getCommandHub().getCommandInvocation(baseCommand.getClass());

        try {
            response = CompletableFuture.supplyAsync(() -> {
                return invocation.invoke(baseCommand);
            }).get();
        } catch (Exception e) {
            throw new FrameworkException("CommandBus.sent Method Error: ", e);
        }

        return response; //invocation.invoke(baseCommand);
    }
}
